package api

import (
	"api-getaway/basic/config"
	"api-getaway/basic/model"
	"api-getaway/handler/request"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func VideoAdd(r *gin.Context) {
	var req request.Video
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数失败",
			"data":    err.Error(),
		})
		return
	}

	video := model.Video{
		Title:  req.Title,
		Class:  req.Class,
		Region: req.Region,
		Cover:  req.Cover,
	}

	if err = video.CreateVideo(); err != nil {
		r.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "创建失败",
			"data":    nil,
		})
		return
	}
	r.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "视频信息录入成功",
		"data":    video,
	})
}

func VideoCheckRecordAdd(r *gin.Context) {
	var req request.VideoCheckRecord
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数失败",
			"data":    err.Error(),
		})
		return
	}

	record := model.VideoCheckRecord{
		VideoId:     req.VideoId,
		CheckStatus: req.CheckStatus,
		CheckReason: req.CheckReason,
		CheckUserId: req.CheckUserId,
	}
	if err = record.CreateVideoCheckRecord(); err != nil {
		r.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "创建失败",
			"data":    nil,
		})
		return
	}
	r.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "审核视频成功",
		"data":    record,
	})
}

func VideoList(r *gin.Context) {
	var req request.VideoCheckRecord
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数失败",
			"data":    err.Error(),
		})
		return
	}

	var all []model.Video
	key := fmt.Sprintf("video_list")
	result, _ := config.Rdb.Get(config.Ctx, key).Result()
	if result != "" {
		json.Unmarshal([]byte(result), &all)
	} else {
		config.DB.Debug().Find(&all)
		marshal, _ := json.Marshal(all)
		config.Rdb.Set(config.Ctx, key, marshal, time.Minute*5)
	}

	r.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "视频查询成功",
		"data":    all,
	})
}

func VideoShow(r *gin.Context) {
	var req request.VideoCheckRecord
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数失败",
			"data":    err.Error(),
		})
		return
	}

	var all model.Video
	config.DB.Debug().Find(&all)
	r.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "视频详情成功",
		"data":    all,
	})
}

func VideoEpisodeList(r *gin.Context) {
	var req request.VideoEpisode
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "参数失败",
			"data":    err.Error(),
		})
		return
	}

	var all []model.VideoEpisode

	config.DB.Debug().Find(&all)

	r.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "剧集列表展示成功",
		"data":    all,
	})
}
